//
//  CCWebViewViewController.m
//  coninbase_data
//
//  Created by 2.5 on 2021/9/8.
//  Copyright © 2021 ChinaRainbow-iOS. All rights reserved.
//

#import "CCWebViewViewController.h"
#import <WebKit/WebKit.h>
//#import <JShare/JSHAREService.h>
#import <UMShare/UMShare.h>
@interface CCWebViewViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic,strong)WKWebView *webView;
@end

@implementation CCWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    [self customeCCUI];
    
//    UIButton *shareButton = [[UIButton alloc] init];
//    [shareButton setTitle:@"share" forState:UIControlStateNormal];
//    [shareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [shareButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
//    shareButton.titleLabel.font = [UIFont systemFontOfSize:15];
//    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:shareButton];
}
-(void)shareAction
{
    //创建分享消息对象
    UMSocialMessageObject*messageObject =[UMSocialMessageObject messageObject];

    //创建网页内容对象
    UMShareWebpageObject*shareObject =[UMShareWebpageObject shareObjectWithTitle:@"coninbasedata" descr:NotNilStr(self.title) thumImage:[UIImage imageNamed:@"icon"]];
    //设置网页地址
        shareObject.webpageUrl =@"http://mobile.umeng.com/social";

    //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;

    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data,NSError*error){
    if(error){
    NSLog(@"************Share fail with error %@*********",error);
    }else{
    NSLog(@"response data is %@",data);
    }
    }];
    
//    JSHAREMessage *message = [JSHAREMessage message];
//        message.text = NotNilStr(self.title);
//        message.platform = JSHAREPlatformQQ;
//        message.mediaType = JSHAREText;
//        [JSHAREService share:message handler:^(JSHAREState state, NSError *error) {
//              NSLog(@"分享回调");
//        }];
}
-(void)customeCCUI
{
    NSString *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"color"];
    NSString *bottom = [[NSUserDefaults standardUserDefaults] objectForKey:@"bottom"];
    NSString *top = [[NSUserDefaults standardUserDefaults] objectForKey:@"top"];
    if(self.isNormal){
        color = @"0xffffff";
        bottom = @"0";
        top = @"0";
        self.navigationController.navigationBarHidden = NO;
    }
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, -[UIApplication sharedApplication].statusBarFrame.size.height, self.view.ccwidth, -[UIApplication sharedApplication].statusBarFrame.size.height)];
    bgView.backgroundColor = [CCWebViewViewController colorWithHexStr:color];
    [self.view addSubview:bgView];
    
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    configuration.allowsInlineMediaPlayback=true;
    if (@available(iOS 10.0, *)) {
        configuration.mediaTypesRequiringUserActionForPlayback = NO;
        
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;
    } else {
        
    }
    configuration.allowsInlineMediaPlayback = YES;
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    [self.view addSubview:self.webView];
    if([UIApplication sharedApplication].statusBarFrame.size.height>20){
        self.webView.frame = CGRectMake(0, top.doubleValue, self.view.bounds.size.width, self.view.bounds.size.height-top.doubleValue - bottom.doubleValue);
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(-40-bottom.doubleValue);
            make.top.mas_equalTo(top.doubleValue);
        }];
    }else{
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(-bottom.doubleValue);
            make.top.mas_equalTo(top.doubleValue);
        }];
    }
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:NotNilStr(self.baseUrl)]]];
}
+ (UIColor *)colorWithHexStr:(NSString *)hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString];
    CGFloat alpha, red, blue, green;
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 1];
            green = [self colorComponentFrom: colorString start: 1 length: 1];
            blue  = [self colorComponentFrom: colorString start: 2 length: 1];
             break;
         case 4: // #ARGB
             alpha = [self colorComponentFrom: colorString start: 0 length: 1];
             red   = [self colorComponentFrom: colorString start: 1 length: 1];
             green = [self colorComponentFrom: colorString start: 2 length: 1];
             blue  = [self colorComponentFrom: colorString start: 3 length: 1];
             break;
         case 6: // #RRGGBB
             alpha = 1.0f;
             red   = [self colorComponentFrom: colorString start: 0 length: 2];
             green = [self colorComponentFrom: colorString start: 2 length: 2];
             blue  = [self colorComponentFrom: colorString start: 4 length: 2];
             break;
         case 8: // #AARRGGBB
             alpha = [self colorComponentFrom: colorString start: 0 length: 2];
             red   = [self colorComponentFrom: colorString start: 2 length: 2];
             green = [self colorComponentFrom: colorString start: 4 length: 2];
             blue  = [self colorComponentFrom: colorString start: 6 length: 2];
             break;
         default:
             return nil;
             break;
     }
     return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
 }
+ (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length {
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}
// 处理H5的alertview
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (NSString *)CCURLEncodeString:(NSString *)sourceUrl {
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *encodedString = [sourceUrl stringByAddingPercentEncodingWithAllowedCharacters:set];
    return encodedString;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
        decisionHandler(WKNavigationActionPolicyAllow);
}
@end
